* (bug 3487) Fix category edit preview with preview-on-bottom
[lhc/web/wiklou.git] / includes / EditPage.php
1 <?php
2 /**
3 * Contain the EditPage class
4 * @package MediaWiki
5 */
6
7 /**
8 * Splitting edit page/HTML interface from Article...
9 * The actual database and text munging is still in Article,
10 * but it should get easier to call those from alternate
11 * interfaces.
12 *
13 * @package MediaWiki
14 */
15
16 class EditPage {
17 var $mArticle;
18 var $mTitle;
19 var $mMetaData = '';
20 var $isConflict = false;
21 var $isCssJsSubpage = false;
22 var $deletedSinceEdit = false;
23 var $formtype;
24 var $firsttime;
25 var $lastDelete;
26 var $mTokenOk = true;
27
28 # Form values
29 var $save = false, $preview = false, $diff = false;
30 var $minoredit = false, $watchthis = false, $recreate = false;
31 var $textbox1 = '', $textbox2 = '', $summary = '';
32 var $edittime = '', $section = '', $starttime = '';
33 var $oldid = 0, $editintro = '', $scrolltop = null;
34
35 /**
36 * @todo document
37 * @param $article
38 */
39 function EditPage( $article ) {
40 $this->mArticle =& $article;
41 global $wgTitle;
42 $this->mTitle =& $wgTitle;
43 }
44
45 /**
46 * This is the function that extracts metadata from the article body on the first view.
47 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
48 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
49 */
50 function extractMetaDataFromArticle () {
51 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
52 $this->mMetaData = '' ;
53 if ( !$wgUseMetadataEdit ) return ;
54 if ( $wgMetadataWhitelist == '' ) return ;
55 $s = '' ;
56 $t = $this->mArticle->getContent ( true ) ;
57
58 # MISSING : <nowiki> filtering
59
60 # Categories and language links
61 $t = explode ( "\n" , $t ) ;
62 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY ) ) ;
63 $cat = $ll = array() ;
64 foreach ( $t AS $key => $x )
65 {
66 $y = trim ( strtolower ( $x ) ) ;
67 while ( substr ( $y , 0 , 2 ) == '[[' )
68 {
69 $y = explode ( ']]' , trim ( $x ) ) ;
70 $first = array_shift ( $y ) ;
71 $first = explode ( ':' , $first ) ;
72 $ns = array_shift ( $first ) ;
73 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
74 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
75 {
76 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
77 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
78 else $ll[] = $add ;
79 $x = implode ( ']]' , $y ) ;
80 $t[$key] = $x ;
81 $y = trim ( strtolower ( $x ) ) ;
82 }
83 }
84 }
85 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
86 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
87 $t = implode ( "\n" , $t ) ;
88
89 # Load whitelist
90 $sat = array () ; # stand-alone-templates; must be lowercase
91 $wl_title = Title::newFromText ( $wgMetadataWhitelist ) ;
92 $wl_article = new Article ( $wl_title ) ;
93 $wl = explode ( "\n" , $wl_article->getContent(true) ) ;
94 foreach ( $wl AS $x )
95 {
96 $isentry = false ;
97 $x = trim ( $x ) ;
98 while ( substr ( $x , 0 , 1 ) == '*' )
99 {
100 $isentry = true ;
101 $x = trim ( substr ( $x , 1 ) ) ;
102 }
103 if ( $isentry )
104 {
105 $sat[] = strtolower ( $x ) ;
106 }
107
108 }
109
110 # Templates, but only some
111 $t = explode ( '{{' , $t ) ;
112 $tl = array () ;
113 foreach ( $t AS $key => $x )
114 {
115 $y = explode ( '}}' , $x , 2 ) ;
116 if ( count ( $y ) == 2 )
117 {
118 $z = $y[0] ;
119 $z = explode ( '|' , $z ) ;
120 $tn = array_shift ( $z ) ;
121 if ( in_array ( strtolower ( $tn ) , $sat ) )
122 {
123 $tl[] = '{{' . $y[0] . '}}' ;
124 $t[$key] = $y[1] ;
125 $y = explode ( '}}' , $y[1] , 2 ) ;
126 }
127 else $t[$key] = '{{' . $x ;
128 }
129 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
130 else $t[$key] = $x ;
131 }
132 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
133 $t = implode ( '' , $t ) ;
134
135 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
136 $this->mArticle->mContent = $t ;
137 $this->mMetaData = $s ;
138 }
139
140 function submit() {
141 $this->edit();
142 }
143
144 /**
145 * This is the function that gets called for "action=edit". It
146 * sets up various member variables, then passes execution to
147 * another function, usually showEditForm()
148 *
149 * The edit form is self-submitting, so that when things like
150 * preview and edit conflicts occur, we get the same form back
151 * with the extra stuff added. Only when the final submission
152 * is made and all is well do we actually save and redirect to
153 * the newly-edited page.
154 */
155 function edit() {
156 global $wgOut, $wgUser, $wgRequest, $wgTitle;
157
158 $fname = 'EditPage::edit';
159 wfProfileIn( $fname );
160 wfDebug( "$fname: enter\n" );
161
162 // this is not an article
163 $wgOut->setArticleFlag(false);
164
165 $this->importFormData( $wgRequest );
166 $this->firsttime = false;
167
168 if( $this->live ) {
169 $this->livePreview();
170 wfProfileOut( $fname );
171 return;
172 }
173
174 if ( ! $this->mTitle->userCanEdit() ) {
175 wfDebug( "$fname: user can't edit\n" );
176 $wgOut->readOnlyPage( $this->mArticle->getContent( true ), true );
177 wfProfileOut( $fname );
178 return;
179 }
180 wfDebug( "$fname: Checking blocks\n" );
181 if ( !$this->preview && !$this->diff && $wgUser->isBlockedFrom( $this->mTitle, !$this->save ) ) {
182 # When previewing, don't check blocked state - will get caught at save time.
183 # Also, check when starting edition is done against slave to improve performance.
184 wfDebug( "$fname: user is blocked\n" );
185 $this->blockedIPpage();
186 wfProfileOut( $fname );
187 return;
188 }
189 if ( !$wgUser->isAllowed('edit') ) {
190 if ( $wgUser->isAnon() ) {
191 wfDebug( "$fname: user must log in\n" );
192 $this->userNotLoggedInPage();
193 wfProfileOut( $fname );
194 return;
195 } else {
196 wfDebug( "$fname: read-only page\n" );
197 $wgOut->readOnlyPage( $this->mArticle->getContent( true ), true );
198 wfProfileOut( $fname );
199 return;
200 }
201 }
202 if ( wfReadOnly() ) {
203 wfDebug( "$fname: read-only mode is engaged\n" );
204 if( $this->save || $this->preview ) {
205 $this->formtype = 'preview';
206 } else if ( $this->diff ) {
207 $this->formtype = 'diff';
208 } else {
209 $wgOut->readOnlyPage( $this->mArticle->getContent( true ) );
210 wfProfileOut( $fname );
211 return;
212 }
213 } else {
214 if ( $this->save ) {
215 $this->formtype = 'save';
216 } else if ( $this->preview ) {
217 $this->formtype = 'preview';
218 } else if ( $this->diff ) {
219 $this->formtype = 'diff';
220 } else { # First time through
221 $this->firsttime = true;
222 if( $this->previewOnOpen() ) {
223 $this->formtype = 'preview';
224 } else {
225 $this->extractMetaDataFromArticle () ;
226 $this->formtype = 'initial';
227 }
228 }
229 }
230
231 wfProfileIn( "$fname-business-end" );
232
233 $this->isConflict = false;
234 // css / js subpages of user pages get a special treatment
235 $this->isCssJsSubpage = $wgTitle->isCssJsSubpage();
236
237 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
238 * no matter it's current state
239 */
240 $this->deletedSinceEdit = false;
241 if ( $this->edittime != '' ) {
242 /* Note that we rely on logging table, which hasn't been always there,
243 * but that doesn't matter, because this only applies to brand new
244 * deletes. This is done on every preview and save request. Move it further down
245 * to only perform it on saves
246 */
247 if ( $this->mTitle->isDeleted() ) {
248 $this->lastDelete = $this->getLastDelete();
249 if ( !is_null($this->lastDelete) ) {
250 $deletetime = $this->lastDelete->log_timestamp;
251 if ( ($deletetime - $this->starttime) > 0 ) {
252 $this->deletedSinceEdit = true;
253 }
254 }
255 }
256 }
257
258 if(!$this->mTitle->getArticleID() && ('initial' == $this->formtype || $this->firsttime )) { # new article
259 $this->showIntro();
260 }
261 if( $this->mTitle->isTalkPage() ) {
262 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
263 }
264
265 # Attempt submission here. This will check for edit conflicts,
266 # and redundantly check for locked database, blocked IPs, etc.
267 # that edit() already checked just in case someone tries to sneak
268 # in the back door with a hand-edited submission URL.
269
270 if ( 'save' == $this->formtype ) {
271 if ( !$this->attemptSave() ) {
272 wfProfileOut( "$fname-business-end" );
273 wfProfileOut( $fname );
274 return;
275 }
276 }
277
278 # First time through: get contents, set time for conflict
279 # checking, etc.
280 if ( 'initial' == $this->formtype || $this->firsttime ) {
281 $this->initialiseForm();
282 }
283
284 $this->showEditForm();
285 wfProfileOut( "$fname-business-end" );
286 wfProfileOut( $fname );
287 }
288
289 /**
290 * Return true if this page should be previewed when the edit form
291 * is initially opened.
292 * @return bool
293 * @access private
294 */
295 function previewOnOpen() {
296 global $wgUser;
297 return $wgUser->getOption( 'previewonfirst' ) ||
298 ( $this->mTitle->getNamespace() == NS_CATEGORY &&
299 !$this->mTitle->exists() );
300 }
301
302 /**
303 * @todo document
304 */
305 function importFormData( &$request ) {
306 global $wgLang ;
307 $fname = 'EditPage::importFormData';
308 wfProfileIn( $fname );
309
310 if( $request->wasPosted() ) {
311 # These fields need to be checked for encoding.
312 # Also remove trailing whitespace, but don't remove _initial_
313 # whitespace from the text boxes. This may be significant formatting.
314 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
315 $this->textbox2 = $this->safeUnicodeInput( $request, 'wpTextbox2' );
316 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
317 # Truncate for whole multibyte characters. +5 bytes for ellipsis
318 $this->summary = $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
319
320 $this->edittime = $request->getVal( 'wpEdittime' );
321 $this->starttime = $request->getVal( 'wpStarttime' );
322
323 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
324
325 if( is_null( $this->edittime ) ) {
326 # If the form is incomplete, force to preview.
327 wfDebug( "$fname: Form data appears to be incomplete\n" );
328 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
329 $this->preview = true;
330 } else {
331 $this->preview = $request->getCheck( 'wpPreview' );
332 $this->diff = $request->getCheck( 'wpDiff' );
333
334 if( !$this->preview ) {
335 if ( $this->tokenOk( $request ) ) {
336 # Some browsers will not report any submit button
337 # if the user hits enter in the comment box.
338 # The unmarked state will be assumed to be a save,
339 # if the form seems otherwise complete.
340 wfDebug( "$fname: Passed token check.\n" );
341 } else {
342 # Page might be a hack attempt posted from
343 # an external site. Preview instead of saving.
344 wfDebug( "$fname: Failed token check; forcing preview\n" );
345 $this->preview = true;
346 }
347 }
348 }
349 $this->save = ! ( $this->preview OR $this->diff );
350 if( !preg_match( '/^\d{14}$/', $this->edittime )) {
351 $this->edittime = null;
352 }
353
354 if( !preg_match( '/^\d{14}$/', $this->starttime )) {
355 $this->starttime = null;
356 }
357
358 $this->recreate = $request->getCheck( 'wpRecreate' );
359
360 $this->minoredit = $request->getCheck( 'wpMinoredit' );
361 $this->watchthis = $request->getCheck( 'wpWatchthis' );
362 } else {
363 # Not a posted form? Start with nothing.
364 wfDebug( "$fname: Not a posted form.\n" );
365 $this->textbox1 = '';
366 $this->textbox2 = '';
367 $this->mMetaData = '';
368 $this->summary = '';
369 $this->edittime = '';
370 $this->starttime = wfTimestampNow();
371 $this->preview = false;
372 $this->save = false;
373 $this->diff = false;
374 $this->minoredit = false;
375 $this->watchthis = false;
376 $this->recreate = false;
377 }
378
379 $this->oldid = $request->getInt( 'oldid' );
380
381 # Section edit can come from either the form or a link
382 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
383
384 $this->live = $request->getCheck( 'live' );
385 $this->editintro = $request->getText( 'editintro' );
386
387 wfProfileOut( $fname );
388 }
389
390 /**
391 * Make sure the form isn't faking a user's credentials.
392 *
393 * @param WebRequest $request
394 * @return bool
395 * @access private
396 */
397 function tokenOk( &$request ) {
398 global $wgUser;
399 if( $wgUser->isAnon() ) {
400 # Anonymous users may not have a session
401 # open. Don't tokenize.
402 $this->mTokenOk = true;
403 } else {
404 $this->mTokenOk = $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
405 }
406 return $this->mTokenOk;
407 }
408
409 function showIntro() {
410 global $wgOut, $wgUser;
411 $addstandardintro=true;
412 if($this->editintro) {
413 $introtitle=Title::newFromText($this->editintro);
414 if(isset($introtitle) && $introtitle->userCanRead()) {
415 $rev=Revision::newFromTitle($introtitle);
416 if($rev) {
417 $wgOut->addWikiText($rev->getText());
418 $addstandardintro=false;
419 }
420 }
421 }
422 if($addstandardintro) {
423 if ( $wgUser->isLoggedIn() )
424 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
425 else
426 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
427 }
428 }
429
430 /**
431 * Attempt submission
432 * @return bool false if output is done, true if the rest of the form should be displayed
433 */
434 function attemptSave() {
435 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
436
437 $fname = 'EditPage::attemptSave';
438 wfProfileIn( $fname );
439 wfProfileIn( "$fname-checks" );
440
441 # Reintegrate metadata
442 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
443 $this->mMetaData = '' ;
444
445 # Check for spam
446 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
447 $this->spamPage ( $matches[0] );
448 wfProfileOut( "$fname-checks" );
449 wfProfileOut( $fname );
450 return false;
451 }
452 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
453 # Error messages or other handling should be performed by the filter function
454 wfProfileOut( $fname );
455 wfProfileOut( "$fname-checks" );
456 return false;
457 }
458 if ( !wfRunHooks( 'EditFilter', array( &$this, $this->textbox1, $this->section ) ) ) {
459 # Error messages or other handling should be performed by the filter function
460 wfProfileOut( $fname );
461 wfProfileOut( "$fname-checks" );
462 return false;
463 }
464 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
465 # Check block state against master, thus 'false'.
466 $this->blockedIPpage();
467 wfProfileOut( "$fname-checks" );
468 wfProfileOut( $fname );
469 return false;
470 }
471
472 if ( !$wgUser->isAllowed('edit') ) {
473 if ( $wgUser->isAnon() ) {
474 $this->userNotLoggedInPage();
475 wfProfileOut( "$fname-checks" );
476 wfProfileOut( $fname );
477 return false;
478 }
479 else {
480 $wgOut->readOnlyPage();
481 wfProfileOut( "$fname-checks" );
482 wfProfileOut( $fname );
483 return false;
484 }
485 }
486
487 if ( wfReadOnly() ) {
488 $wgOut->readOnlyPage();
489 wfProfileOut( "$fname-checks" );
490 wfProfileOut( $fname );
491 return false;
492 }
493 if ( $wgUser->pingLimiter() ) {
494 $wgOut->rateLimited();
495 wfProfileOut( "$fname-checks" );
496 wfProfileOut( $fname );
497 return false;
498 }
499
500 # If the article has been deleted while editing, don't save it without
501 # confirmation
502 if ( $this->deletedSinceEdit && !$this->recreate ) {
503 wfProfileOut( "$fname-checks" );
504 wfProfileOut( $fname );
505 return true;
506 }
507
508 wfProfileOut( "$fname-checks" );
509
510 # If article is new, insert it.
511 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
512 if ( 0 == $aid ) {
513 # Don't save a new article if it's blank.
514 if ( ( '' == $this->textbox1 ) ) {
515 $wgOut->redirect( $this->mTitle->getFullURL() );
516 wfProfileOut( $fname );
517 return false;
518 }
519
520 $isComment=($this->section=='new');
521 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
522 $this->minoredit, $this->watchthis, false, $isComment);
523
524 wfProfileOut( $fname );
525 return false;
526 }
527
528 # Article exists. Check for edit conflict.
529
530 $this->mArticle->clear(); # Force reload of dates, etc.
531 $this->mArticle->forUpdate( true ); # Lock the article
532
533 if( ( $this->section != 'new' ) &&
534 ($this->mArticle->getTimestamp() != $this->edittime ) )
535 {
536 $this->isConflict = true;
537 }
538 $userid = $wgUser->getID();
539
540 if ( $this->isConflict) {
541 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
542 $this->mArticle->getTimestamp() . "'\n" );
543 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime);
544 }
545 else {
546 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
547 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary);
548 }
549 if( is_null( $text ) ) {
550 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
551 $this->isConflict = true;
552 $text = $this->textbox1;
553 }
554
555 # Suppress edit conflict with self, except for section edits where merging is required.
556 if ( ( $this->section == '' ) && ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
557 wfDebug( "Suppressing edit conflict, same user.\n" );
558 $this->isConflict = false;
559 } else {
560 # switch from section editing to normal editing in edit conflict
561 if($this->isConflict) {
562 # Attempt merge
563 if( $this->mergeChangesInto( $text ) ){
564 // Successful merge! Maybe we should tell the user the good news?
565 $this->isConflict = false;
566 wfDebug( "Suppressing edit conflict, successful merge.\n" );
567 } else {
568 $this->section = '';
569 $this->textbox1 = $text;
570 wfDebug( "Keeping edit conflict, failed merge.\n" );
571 }
572 }
573 }
574
575 if ( $this->isConflict ) {
576 wfProfileOut( $fname );
577 return true;
578 }
579
580 # All's well
581 wfProfileIn( "$fname-sectionanchor" );
582 $sectionanchor = '';
583 if( $this->section == 'new' ) {
584 if( $this->summary != '' ) {
585 $sectionanchor = $this->sectionAnchor( $this->summary );
586 }
587 } elseif( $this->section != '' ) {
588 # Try to get a section anchor from the section source, redirect to edited section if header found
589 # XXX: might be better to integrate this into Article::replaceSection
590 # for duplicate heading checking and maybe parsing
591 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
592 # we can't deal with anchors, includes, html etc in the header for now,
593 # headline would need to be parsed to improve this
594 if($hasmatch and strlen($matches[2]) > 0) {
595 $sectionanchor = $this->sectionAnchor( $matches[2] );
596 }
597 }
598 wfProfileOut( "$fname-sectionanchor" );
599
600 // Save errors may fall down to the edit form, but we've now
601 // merged the section into full text. Clear the section field
602 // so that later submission of conflict forms won't try to
603 // replace that into a duplicated mess.
604 $this->textbox1 = $text;
605 $this->section = '';
606
607 # update the article here
608 if( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
609 $this->watchthis, '', $sectionanchor ) ) {
610 wfProfileOut( $fname );
611 return false;
612 } else {
613 $this->isConflict = true;
614 }
615 wfProfileOut( $fname );
616 return true;
617 }
618
619 /**
620 * Initialise form fields in the object
621 * Called on the first invocation, e.g. when a user clicks an edit link
622 */
623 function initialiseForm() {
624 $this->edittime = $this->mArticle->getTimestamp();
625 $this->textbox1 = $this->mArticle->getContent( true );
626 $this->summary = '';
627 wfProxyCheck();
628 }
629
630 /**
631 * Send the edit form and related headers to $wgOut
632 * @param $formCallback Optional callable that takes an OutputPage
633 * parameter; will be called during form output
634 * near the top, for captchas and the like.
635 */
636 function showEditForm( $formCallback=null ) {
637 global $wgOut, $wgUser, $wgAllowAnonymousMinor, $wgLang, $wgContLang;
638
639 $fname = 'EditPage::showEditForm';
640 wfProfileIn( $fname );
641
642 $sk =& $wgUser->getSkin();
643
644 $wgOut->setRobotpolicy( 'noindex,nofollow' );
645
646 # Enabled article-related sidebar, toplinks, etc.
647 $wgOut->setArticleRelated( true );
648
649 if ( $this->isConflict ) {
650 $s = wfMsg( 'editconflict', $this->mTitle->getPrefixedText() );
651 $wgOut->setPageTitle( $s );
652 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
653
654 $this->textbox2 = $this->textbox1;
655 $this->textbox1 = $this->mArticle->getContent( true );
656 $this->edittime = $this->mArticle->getTimestamp();
657 } else {
658
659 if( $this->section != '' ) {
660 if( $this->section == 'new' ) {
661 $s = wfMsg('editingcomment', $this->mTitle->getPrefixedText() );
662 } else {
663 $s = wfMsg('editingsection', $this->mTitle->getPrefixedText() );
664 if( !$this->preview && !$this->diff ) {
665 preg_match( "/^(=+)(.+)\\1/mi",
666 $this->textbox1,
667 $matches );
668 if( !empty( $matches[2] ) ) {
669 $this->summary = "/* ". trim($matches[2])." */ ";
670 }
671 }
672 }
673 } else {
674 $s = wfMsg( 'editing', $this->mTitle->getPrefixedText() );
675 }
676 $wgOut->setPageTitle( $s );
677 if ( !$this->checkUnicodeCompliantBrowser() ) {
678 $this->mArticle->setOldSubtitle();
679 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
680 }
681 if ( isset( $this->mArticle )
682 && isset( $this->mArticle->mRevision )
683 && !$this->mArticle->mRevision->isCurrent() ) {
684 $this->mArticle->setOldSubtitle();
685 $wgOut->addWikiText( wfMsg( 'editingold' ) );
686 }
687 }
688
689 if( wfReadOnly() ) {
690 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
691 } else if ( $this->isCssJsSubpage and 'preview' != $this->formtype) {
692 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ));
693 }
694 if( $this->mTitle->isProtected('edit') ) {
695 $wgOut->addWikiText( wfMsg( 'protectedpagewarning' ) );
696 }
697
698 $kblength = (int)(strlen( $this->textbox1 ) / 1024);
699 if( $kblength > 29 ) {
700 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $kblength ) ) );
701 }
702
703 $rows = $wgUser->getOption( 'rows' );
704 $cols = $wgUser->getOption( 'cols' );
705
706 $ew = $wgUser->getOption( 'editwidth' );
707 if ( $ew ) $ew = " style=\"width:100%\"";
708 else $ew = '';
709
710 $q = 'action=submit';
711 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
712 $action = $this->mTitle->escapeLocalURL( $q );
713
714 $summary = wfMsg('summary');
715 $subject = wfMsg('subject');
716 $minor = wfMsg('minoredit');
717 $watchthis = wfMsg ('watchthis');
718 $save = wfMsg('savearticle');
719 $prev = wfMsg('showpreview');
720 $diff = wfMsg('showdiff');
721
722 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
723 wfMsg('cancel') );
724 $edithelpurl = $sk->makeInternalOrExternalUrl( wfMsg( 'edithelppage' ));
725 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
726 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
727 htmlspecialchars( wfMsg( 'newwindow' ) );
728
729 global $wgRightsText;
730 $copywarn = "<div id=\"editpage-copywarn\">\n" .
731 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
732 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
733 $wgRightsText ) . "\n</div>";
734
735 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
736 # prepare toolbar for edit buttons
737 $toolbar = $this->getEditToolbar();
738 } else {
739 $toolbar = '';
740 }
741
742 // activate checkboxes if user wants them to be always active
743 if( !$this->preview && !$this->diff ) {
744 if( $wgUser->getOption( 'watchdefault' ) ) $this->watchthis = true;
745 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
746
747 // activate checkbox also if user is already watching the page,
748 // require wpWatchthis to be unset so that second condition is not
749 // checked unnecessarily
750 if( !$this->watchthis && $this->mTitle->userIsWatching() ) $this->watchthis = true;
751 }
752
753 $minoredithtml = '';
754
755 if ( $wgUser->isLoggedIn() || $wgAllowAnonymousMinor ) {
756 $minoredithtml =
757 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?" checked='checked'":"").
758 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
759 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
760 }
761
762 $watchhtml = '';
763
764 if ( $wgUser->isLoggedIn() ) {
765 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
766 ($this->watchthis?" checked='checked'":"").
767 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />".
768 "<label for='wpWatchthis' title=\"" .
769 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>";
770 }
771
772 $checkboxhtml = $minoredithtml . $watchhtml;
773
774 if ( 'preview' == $this->formtype && $wgUser->getOption( 'previewontop' ) ) {
775 $this->showPreview();
776 }
777 if ( 'diff' == $this->formtype ) {
778 if ( $wgUser->getOption('previewontop' ) ) {
779 $wgOut->addHTML( $this->getDiff() );
780 }
781 }
782
783
784 # if this is a comment, show a subject line at the top, which is also the edit summary.
785 # Otherwise, show a summary field at the bottom
786 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
787 if( $this->section == 'new' ) {
788 $commentsubject="<span id='wpSummaryLabel'><label for='wpSummary'>{$subject}:</label></span> <div class='editOptions'><input tabindex='1' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
789 $editsummary = '';
790 } else {
791 $commentsubject = '';
792 $editsummary="<span id='wpSummaryLabel'><label for='wpSummary'>{$summary}:</label></span> <div class='editOptions'><input tabindex='2' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
793 }
794
795 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
796 if( !$this->preview && !$this->diff ) {
797 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
798 }
799 $templates = $this->getTemplatesUsed();
800
801 global $wgLivePreview;
802 if ( $wgLivePreview ) {
803 $liveOnclick = $this->doLivePreviewScript();
804 } else {
805 $liveOnclick = '';
806 }
807
808 global $wgUseMetadataEdit ;
809 if ( $wgUseMetadataEdit ) {
810 $metadata = $this->mMetaData ;
811 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
812 $helppage = Title::newFromText( wfMsg( "metadata_page" ) ) ;
813 $top = wfMsg( 'metadata', $helppage->getInternalURL() );
814 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
815 }
816 else $metadata = "" ;
817
818 $hidden = '';
819 $recreate = '';
820 if ($this->deletedSinceEdit) {
821 if ( 'save' != $this->formtype ) {
822 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
823 } else {
824 // Hide the toolbar and edit area, use can click preview to get it back
825 // Add an confirmation checkbox and explanation.
826 $toolbar = '';
827 $hidden = 'type="hidden" style="display:none;"';
828 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
829 $recreate .=
830 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
831 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
832 }
833 }
834
835 $safemodehtml = $this->checkUnicodeCompliantBrowser()
836 ? ""
837 : "<input type='hidden' name=\"safemode\" value='1' />\n";
838
839 $wgOut->addHTML( <<<END
840 {$toolbar}
841 <form id="editform" name="editform" method="post" action="$action"
842 enctype="multipart/form-data">
843 END
844 );
845 if( is_callable( $formCallback ) ) {
846 call_user_func_array( $formCallback, array( &$wgOut ) );
847 }
848 $wgOut->addHTML( <<<END
849 $recreate
850 {$commentsubject}
851 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
852 cols='{$cols}'{$ew} $hidden>
853 END
854 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
855 "
856 </textarea><br />
857 {$metadata}
858 {$editsummary}
859 {$checkboxhtml}
860 {$safemodehtml}
861 <div class='editButtons'>
862 <input tabindex='5' id='wpSave' type='submit' value=\"{$save}\" name=\"wpSave\" accesskey=\"".wfMsg('accesskey-save')."\"".
863 " title=\"".wfMsg('tooltip-save')."\"/>
864 <input tabindex='6' id='wpPreview' type='submit' $liveOnclick value=\"{$prev}\" name=\"wpPreview\" accesskey=\"".wfMsg('accesskey-preview')."\"".
865 " title=\"".wfMsg('tooltip-preview')."\"/>
866 <input tabindex='7' id='wpDiff' type='submit' value=\"{$diff}\" name=\"wpDiff\" accesskey=\"".wfMsg('accesskey-diff')."\"".
867 " title=\"".wfMsg('tooltip-diff')."\"/> <span class='editHelp'>{$cancel} | {$edithelp}</span></div>
868 </div>
869 <div class='templatesUsed'>
870 {$templates}
871 </div>
872 " );
873 $wgOut->addWikiText( $copywarn );
874 $wgOut->addHTML( "
875 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
876 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
877 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
878 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
879
880 if ( $wgUser->isLoggedIn() ) {
881 /**
882 * To make it harder for someone to slip a user a page
883 * which submits an edit form to the wiki without their
884 * knowledge, a random token is associated with the login
885 * session. If it's not passed back with the submission,
886 * we won't save the page, or render user JavaScript and
887 * CSS previews.
888 */
889 $token = htmlspecialchars( $wgUser->editToken() );
890 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
891 }
892
893
894 if ( $this->isConflict ) {
895 require_once( "DifferenceEngine.php" );
896 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
897 DifferenceEngine::showDiff( $this->textbox2, $this->textbox1,
898 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
899
900 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
901 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
902 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
903 }
904 $wgOut->addHTML( "</form>\n" );
905 if ( $this->formtype == 'preview' && !$wgUser->getOption( 'previewontop' ) ) {
906 $this->showPreview();
907 }
908 if ( $this->formtype == 'diff' && !$wgUser->getOption( 'previewontop' ) ) {
909 #$wgOut->addHTML( '<div id="wikiPreview">' . $difftext . '</div>' );
910 $wgOut->addHTML( $this->getDiff() );
911 }
912
913 wfProfileOut( $fname );
914 }
915
916 /**
917 * Append preview output to $wgOut.
918 * Includes category rendering if this is a category page.
919 * @access private
920 */
921 function showPreview() {
922 global $wgOut;
923 $wgOut->addHTML( '<div id="wikiPreview">' );
924 if($this->mTitle->getNamespace() == NS_CATEGORY) {
925 $this->mArticle->openShowCategory();
926 }
927 $previewOutput = $this->getPreviewText();
928 $wgOut->addHTML( $previewOutput );
929 if($this->mTitle->getNamespace() == NS_CATEGORY) {
930 $this->mArticle->closeShowCategory();
931 }
932 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
933 $wgOut->addHTML( '</div>' );
934 }
935
936 /**
937 * Prepare a list of templates used by this page. Returns HTML.
938 */
939 function getTemplatesUsed() {
940 global $wgUser;
941
942 $fname = 'EditPage::getTemplatesUsed';
943 wfProfileIn( $fname );
944
945 $sk =& $wgUser->getSkin();
946
947 $templates = '';
948 $articleTemplates = $this->mArticle->getUsedTemplates();
949 if ( count( $articleTemplates ) > 0 ) {
950 $templates = '<br />'. wfMsg( 'templatesused' ) . '<ul>';
951 foreach ( $articleTemplates as $tpl ) {
952 if ( $titleObj = Title::makeTitle( NS_TEMPLATE, $tpl ) ) {
953 $templates .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
954 }
955 }
956 $templates .= '</ul>';
957 }
958 wfProfileOut( $fname );
959 return $templates;
960 }
961
962 /**
963 * Live Preview lets us fetch rendered preview page content and
964 * add it to the page without refreshing the whole page.
965 * If not supported by the browser it will fall through to the normal form
966 * submission method.
967 *
968 * This function outputs a script tag to support live preview, and
969 * returns an onclick handler which should be added to the attributes
970 * of the preview button
971 */
972 function doLivePreviewScript() {
973 global $wgStylePath, $wgJsMimeType, $wgOut;
974 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
975 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
976 '"></script>' . "\n" );
977 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
978 return 'onclick="return !livePreview('.
979 'getElementById(\'wikiPreview\'),' .
980 'editform.wpTextbox1.value,' .
981 htmlspecialchars( '"' . $liveAction . '"' ) . ')"';
982 }
983
984 function getLastDelete() {
985 $dbr =& wfGetDB( DB_SLAVE );
986 $fname = 'EditPage::getLastDelete';
987 $res = $dbr->select(
988 array( 'logging', 'user' ),
989 array( 'log_type',
990 'log_action',
991 'log_timestamp',
992 'log_user',
993 'log_namespace',
994 'log_title',
995 'log_comment',
996 'log_params',
997 'user_name', ),
998 array( 'log_namespace' => $this->mTitle->getNamespace(),
999 'log_title' => $this->mTitle->getDBkey(),
1000 'log_type' => 'delete',
1001 'log_action' => 'delete',
1002 'user_id=log_user' ),
1003 $fname,
1004 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1005
1006 if($dbr->numRows($res) == 1) {
1007 while ( $x = $dbr->fetchObject ( $res ) )
1008 $data = $x;
1009 $dbr->freeResult ( $res ) ;
1010 } else {
1011 $data = null;
1012 }
1013 return $data;
1014 }
1015
1016 /**
1017 * @todo document
1018 */
1019 function getPreviewText() {
1020 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgAllowDiffPreview, $wgEnableDiffPreviewPreference;
1021
1022 $fname = 'EditPage::getPreviewText';
1023 wfProfileIn( $fname );
1024
1025 if ( $this->mTokenOk ) {
1026 $msg = 'previewnote';
1027 } else {
1028 $msg = 'session_fail_preview';
1029 }
1030 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1031 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1032 if ( $this->isConflict ) {
1033 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1034 }
1035
1036 $parserOptions = ParserOptions::newFromUser( $wgUser );
1037 $parserOptions->setEditSection( false );
1038
1039 # don't parse user css/js, show message about preview
1040 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1041
1042 if ( $this->isCssJsSubpage ) {
1043 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1044 $previewtext = wfMsg('usercsspreview');
1045 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1046 $previewtext = wfMsg('userjspreview');
1047 }
1048 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1049 $wgOut->addHTML( $parserOutput->mText );
1050 wfProfileOut( $fname );
1051 return $previewhead;
1052 } else {
1053 # if user want to see preview when he edit an article
1054 if( $wgUser->getOption('previewonfirst') and ($this->textbox1 == '')) {
1055 $this->textbox1 = $this->mArticle->getContent(true);
1056 }
1057
1058 $toparse = $this->textbox1;
1059
1060 # If we're adding a comment, we need to show the
1061 # summary as the headline
1062 if($this->section=="new" && $this->summary!="") {
1063 $toparse="== {$this->summary} ==\n\n".$toparse;
1064 }
1065
1066 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1067
1068 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1069 $wgTitle, $parserOptions );
1070
1071 $previewHTML = $parserOutput->mText;
1072
1073 $wgOut->addCategoryLinks($parserOutput->getCategoryLinks());
1074 $wgOut->addLanguageLinks($parserOutput->getLanguageLinks());
1075
1076 wfProfileOut( $fname );
1077 return $previewhead . $previewHTML;
1078 }
1079 }
1080
1081 /**
1082 * @todo document
1083 */
1084 function blockedIPpage() {
1085 global $wgOut, $wgUser, $wgContLang;
1086
1087 $wgOut->setPageTitle( wfMsg( 'blockedtitle' ) );
1088 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1089 $wgOut->setArticleRelated( false );
1090
1091 $id = $wgUser->blockedBy();
1092 $reason = $wgUser->blockedFor();
1093 $ip = wfGetIP();
1094
1095 if ( is_numeric( $id ) ) {
1096 $name = User::whoIs( $id );
1097 } else {
1098 $name = $id;
1099 }
1100 $link = '[[' . $wgContLang->getNsText( NS_USER ) .
1101 ":{$name}|{$name}]]";
1102
1103 $wgOut->addWikiText( wfMsg( 'blockedtext', $link, $reason, $ip, $name ) );
1104 $wgOut->returnToMain( false );
1105 }
1106
1107 /**
1108 * @todo document
1109 */
1110 function userNotLoggedInPage() {
1111 global $wgOut;
1112
1113 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1114 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1115 $wgOut->setArticleRelated( false );
1116
1117 $wgOut->addWikiText( wfMsg( 'whitelistedittext' ) );
1118 $wgOut->returnToMain( false );
1119 }
1120
1121 /**
1122 * @todo document
1123 */
1124 function spamPage ( $match = false )
1125 {
1126 global $wgOut;
1127 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1128 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1129 $wgOut->setArticleRelated( false );
1130
1131 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1132 if ( $match ) {
1133 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1134 }
1135 $wgOut->returnToMain( false );
1136 }
1137
1138 /**
1139 * @access private
1140 * @todo document
1141 */
1142 function mergeChangesInto( &$editText ){
1143 $fname = 'EditPage::mergeChangesInto';
1144 wfProfileIn( $fname );
1145
1146 $db =& wfGetDB( DB_MASTER );
1147
1148 // This is the revision the editor started from
1149 $baseRevision = Revision::loadFromTimestamp(
1150 $db, $this->mArticle->mTitle, $this->edittime );
1151 if( is_null( $baseRevision ) ) {
1152 wfProfileOut( $fname );
1153 return false;
1154 }
1155 $baseText = $baseRevision->getText();
1156
1157 // The current state, we want to merge updates into it
1158 $currentRevision = Revision::loadFromTitle(
1159 $db, $this->mArticle->mTitle );
1160 if( is_null( $currentRevision ) ) {
1161 wfProfileOut( $fname );
1162 return false;
1163 }
1164 $currentText = $currentRevision->getText();
1165
1166 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1167 $editText = $result;
1168 wfProfileOut( $fname );
1169 return true;
1170 } else {
1171 wfProfileOut( $fname );
1172 return false;
1173 }
1174 }
1175
1176 /**
1177 * Check if the browser is on a blacklist of user-agents known to
1178 * mangle UTF-8 data on form submission. Returns true if Unicode
1179 * should make it through, false if it's known to be a problem.
1180 * @return bool
1181 * @access private
1182 */
1183 function checkUnicodeCompliantBrowser() {
1184 global $wgBrowserBlackList;
1185 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1186 // No User-Agent header sent? Trust it by default...
1187 return true;
1188 }
1189 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1190 foreach ( $wgBrowserBlackList as $browser ) {
1191 if ( preg_match($browser, $currentbrowser) ) {
1192 return false;
1193 }
1194 }
1195 return true;
1196 }
1197
1198 /**
1199 * Format an anchor fragment as it would appear for a given section name
1200 * @param string $text
1201 * @return string
1202 * @access private
1203 */
1204 function sectionAnchor( $text ) {
1205 $headline = Sanitizer::decodeCharReferences( $text );
1206 # strip out HTML
1207 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1208 $headline = trim( $headline );
1209 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1210 $replacearray = array(
1211 '%3A' => ':',
1212 '%' => '.'
1213 );
1214 return str_replace(
1215 array_keys( $replacearray ),
1216 array_values( $replacearray ),
1217 $sectionanchor );
1218 }
1219
1220 /**
1221 * Shows a bulletin board style toolbar for common editing functions.
1222 * It can be disabled in the user preferences.
1223 * The necessary JavaScript code can be found in style/wikibits.js.
1224 */
1225 function getEditToolbar() {
1226 global $wgStylePath, $wgLang, $wgMimeType, $wgJsMimeType;
1227
1228 /**
1229 * toolarray an array of arrays which each include the filename of
1230 * the button image (without path), the opening tag, the closing tag,
1231 * and optionally a sample text that is inserted between the two when no
1232 * selection is highlighted.
1233 * The tip text is shown when the user moves the mouse over the button.
1234 *
1235 * Already here are accesskeys (key), which are not used yet until someone
1236 * can figure out a way to make them work in IE. However, we should make
1237 * sure these keys are not defined on the edit page.
1238 */
1239 $toolarray=array(
1240 array( 'image'=>'button_bold.png',
1241 'open' => "\'\'\'",
1242 'close' => "\'\'\'",
1243 'sample'=> wfMsg('bold_sample'),
1244 'tip' => wfMsg('bold_tip'),
1245 'key' => 'B'
1246 ),
1247 array( 'image'=>'button_italic.png',
1248 'open' => "\'\'",
1249 'close' => "\'\'",
1250 'sample'=> wfMsg('italic_sample'),
1251 'tip' => wfMsg('italic_tip'),
1252 'key' => 'I'
1253 ),
1254 array( 'image'=>'button_link.png',
1255 'open' => '[[',
1256 'close' => ']]',
1257 'sample'=> wfMsg('link_sample'),
1258 'tip' => wfMsg('link_tip'),
1259 'key' => 'L'
1260 ),
1261 array( 'image'=>'button_extlink.png',
1262 'open' => '[',
1263 'close' => ']',
1264 'sample'=> wfMsg('extlink_sample'),
1265 'tip' => wfMsg('extlink_tip'),
1266 'key' => 'X'
1267 ),
1268 array( 'image'=>'button_headline.png',
1269 'open' => "\\n== ",
1270 'close' => " ==\\n",
1271 'sample'=> wfMsg('headline_sample'),
1272 'tip' => wfMsg('headline_tip'),
1273 'key' => 'H'
1274 ),
1275 array( 'image'=>'button_image.png',
1276 'open' => '[['.$wgLang->getNsText(NS_IMAGE).":",
1277 'close' => ']]',
1278 'sample'=> wfMsg('image_sample'),
1279 'tip' => wfMsg('image_tip'),
1280 'key' => 'D'
1281 ),
1282 array( 'image' =>'button_media.png',
1283 'open' => '[['.$wgLang->getNsText(NS_MEDIA).':',
1284 'close' => ']]',
1285 'sample'=> wfMsg('media_sample'),
1286 'tip' => wfMsg('media_tip'),
1287 'key' => 'M'
1288 ),
1289 array( 'image' =>'button_math.png',
1290 'open' => "\\<math\\>",
1291 'close' => "\\</math\\>",
1292 'sample'=> wfMsg('math_sample'),
1293 'tip' => wfMsg('math_tip'),
1294 'key' => 'C'
1295 ),
1296 array( 'image' =>'button_nowiki.png',
1297 'open' => "\\<nowiki\\>",
1298 'close' => "\\</nowiki\\>",
1299 'sample'=> wfMsg('nowiki_sample'),
1300 'tip' => wfMsg('nowiki_tip'),
1301 'key' => 'N'
1302 ),
1303 array( 'image' =>'button_sig.png',
1304 'open' => '--~~~~',
1305 'close' => '',
1306 'sample'=> '',
1307 'tip' => wfMsg('sig_tip'),
1308 'key' => 'Y'
1309 ),
1310 array( 'image' =>'button_hr.png',
1311 'open' => "\\n----\\n",
1312 'close' => '',
1313 'sample'=> '',
1314 'tip' => wfMsg('hr_tip'),
1315 'key' => 'R'
1316 )
1317 );
1318 $toolbar ="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1319
1320 $toolbar.="document.writeln(\"<div id='toolbar'>\");\n";
1321 foreach($toolarray as $tool) {
1322
1323 $image=$wgStylePath.'/common/images/'.$tool['image'];
1324 $open=$tool['open'];
1325 $close=$tool['close'];
1326 $sample = wfEscapeJsString( $tool['sample'] );
1327
1328 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1329 // Older browsers show a "speedtip" type message only for ALT.
1330 // Ideally these should be different, realistically they
1331 // probably don't need to be.
1332 $tip = wfEscapeJsString( $tool['tip'] );
1333
1334 #$key = $tool["key"];
1335
1336 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1337 }
1338
1339 $toolbar.="document.writeln(\"</div>\");\n";
1340 $toolbar.="/*]]>*/\n</script>";
1341 return $toolbar;
1342 }
1343
1344 /**
1345 * Output preview text only. This can be sucked into the edit page
1346 * via JavaScript, and saves the server time rendering the skin as
1347 * well as theoretically being more robust on the client (doesn't
1348 * disturb the edit box's undo history, won't eat your text on
1349 * failure, etc).
1350 *
1351 * @todo This doesn't include category or interlanguage links.
1352 * Would need to enhance it a bit, maybe wrap them in XML
1353 * or something... that might also require more skin
1354 * initialization, so check whether that's a problem.
1355 */
1356 function livePreview() {
1357 global $wgOut;
1358 $wgOut->disable();
1359 header( 'Content-type: text/xml' );
1360 header( 'Cache-control: no-cache' );
1361 # FIXME
1362 echo $this->getPreviewText( false, false );
1363 }
1364
1365
1366 /**
1367 * Get a diff between the current contents of the edit box and the
1368 * version of the page we're editing from.
1369 *
1370 * If this is a section edit, we'll replace the section as for final
1371 * save and then make a comparison.
1372 *
1373 * @return string HTML
1374 */
1375 function getDiff() {
1376 global $wgUser;
1377
1378 require_once( 'DifferenceEngine.php' );
1379 $oldtext = $this->mArticle->fetchContent();
1380 $newtext = $this->mArticle->replaceSection(
1381 $this->section, $this->textbox1, $this->summary, $this->edittime );
1382 $oldtitle = wfMsg( 'currentrev' );
1383 $newtitle = wfMsg( 'yourtext' );
1384 if ( $oldtext != wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) || $newtext != '' ) {
1385 $difftext = DifferenceEngine::getDiff( $oldtext, $newtext, $oldtitle, $newtitle );
1386 }
1387
1388 return '<div id="wikiDiff">' . $difftext . '</div>';
1389 }
1390
1391 /**
1392 * Filter an input field through a Unicode de-armoring process if it
1393 * came from an old browser with known broken Unicode editing issues.
1394 *
1395 * @param WebRequest $request
1396 * @param string $field
1397 * @return string
1398 * @access private
1399 */
1400 function safeUnicodeInput( $request, $field ) {
1401 $text = rtrim( $request->getText( $field ) );
1402 return $request->getBool( 'safemode' )
1403 ? $this->unmakesafe( $text )
1404 : $text;
1405 }
1406
1407 /**
1408 * Filter an output field through a Unicode armoring process if it is
1409 * going to an old browser with known broken Unicode editing issues.
1410 *
1411 * @param string $text
1412 * @return string
1413 * @access private
1414 */
1415 function safeUnicodeOutput( $text ) {
1416 global $wgContLang;
1417 $codedText = $wgContLang->recodeForEdit( $text );
1418 return $this->checkUnicodeCompliantBrowser()
1419 ? $codedText
1420 : $this->makesafe( $codedText );
1421 }
1422
1423 /**
1424 * A number of web browsers are known to corrupt non-ASCII characters
1425 * in a UTF-8 text editing environment. To protect against this,
1426 * detected browsers will be served an armored version of the text,
1427 * with non-ASCII chars converted to numeric HTML character references.
1428 *
1429 * Preexisting such character references will have a 0 added to them
1430 * to ensure that round-trips do not alter the original data.
1431 *
1432 * @param string $invalue
1433 * @return string
1434 * @access private
1435 */
1436 function makesafe( $invalue ) {
1437 // Armor existing references for reversability.
1438 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
1439
1440 $bytesleft = 0;
1441 $result = "";
1442 $working = 0;
1443 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1444 $bytevalue = ord( $invalue{$i} );
1445 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1446 $result .= chr( $bytevalue );
1447 $bytesleft = 0;
1448 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1449 $working = $working << 6;
1450 $working += ($bytevalue & 0x3F);
1451 $bytesleft--;
1452 if( $bytesleft <= 0 ) {
1453 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1454 }
1455 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1456 $working = $bytevalue & 0x1F;
1457 $bytesleft = 1;
1458 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1459 $working = $bytevalue & 0x0F;
1460 $bytesleft = 2;
1461 } else { //1111 0xxx
1462 $working = $bytevalue & 0x07;
1463 $bytesleft = 3;
1464 }
1465 }
1466 return $result;
1467 }
1468
1469 /**
1470 * Reverse the previously applied transliteration of non-ASCII characters
1471 * back to UTF-8. Used to protect data from corruption by broken web browsers
1472 * as listed in $wgBrowserBlackList.
1473 *
1474 * @param string $invalue
1475 * @return string
1476 * @access private
1477 */
1478 function unmakesafe( $invalue ) {
1479 $result = "";
1480 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1481 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
1482 $i += 3;
1483 $hexstring = "";
1484 do {
1485 $hexstring .= $invalue{$i};
1486 $i++;
1487 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1488
1489 // Do some sanity checks. These aren't needed for reversability,
1490 // but should help keep the breakage down if the editor
1491 // breaks one of the entities whilst editing.
1492 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1493 $codepoint = hexdec($hexstring);
1494 $result .= codepointToUtf8( $codepoint );
1495 } else {
1496 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1497 }
1498 } else {
1499 $result .= substr( $invalue, $i, 1 );
1500 }
1501 }
1502 // reverse the transform that we made for reversability reasons.
1503 return strtr( $result, array( "&#x0" => "&#x" ) );
1504 }
1505
1506
1507 }
1508
1509 ?>